package com.wmada.toolkit.wxreformat;

import com.wmada.toolkit.common.bean.ActionResult;
import com.wmada.toolkit.common.bean.FailureActionResult;
import com.wmada.toolkit.common.bean.SuccessActionResult;
import com.wmada.toolkit.common.secure.SHA1Utils;
import com.wmada.toolkit.rest.Downloader;
import com.wmada.toolkit.rest.Response;

import java.io.File;

/**
 * @author will.ma
 * @date 2020-11-6
 */
public class WeChatDownloader {

    private final Downloader downloader = new Downloader();

    private final String url;

    private String basePath;

    private String html = null;

    public WeChatDownloader(String url) {
        this.url = url;

        init();
    }

    public Downloader getDownloader() {
        return downloader;
    }

    public Response getResponse() {
        return downloader.getLastResponse();
    }

    private void init() {
        if (html == null) {
            downloader.reset().get(url);
            downloader.withLastResponseCookie();
            downloader.withReferer(url);
        }
    }

    public String getUrl() {
        return url;
    }

    public String getHtml() {
        if (html == null) {
            html = getResponse().getString();
            downloader.setReferer(url);
        }
        return html;
    }

    public String getBasePath() {
        return basePath;
    }

    public void setBasePath(String basePath) {
        this.basePath = basePath;
    }

    public ActionResult<File> getFile(String url, Downloader.EntityMode mode) {
        Response response = downloader.withMode(mode).get(url);
        if (response.isOk()) {
            File file = response.save(basePath, SHA1Utils.getDigest(url));
            return new SuccessActionResult<>(file);
        } else {
            return new FailureActionResult<>(response.getMessage());
        }
    }

}
